
class Player {
    index: number;
    opponents: number[] = []; // 房间内对手的序号list
    oppoIndex = 0; // 在对手中不断轮转的index
    constructor(index: number) {
        this.index = index;
    }

    setOpponents(num: number) {
        this.opponents = [];
        for (let index = 1, len = num; index <= len; index++) {
            if (index != this.index) {
                this.opponents.push(index);
            }
        }
        this.oppoIndex = this.index - 1;
        this.oppoIndex = this.oppoIndex % this.opponents.length;
        console.log("player index ", this.index, "opps: ", this.opponents);
    }

    onRemovePlayer(playerIndex: number) {
        // 根据要删除的序号确定oppoIndex是否需要改
        let needChangeOppo = false;
        for (let index = 0, len = this.opponents.length; index < len; index++) {
            if (this.opponents[index] === playerIndex) {
                if (index > this.oppoIndex) {
                    needChangeOppo = true;
                }
                this.opponents.splice(index, 1);
                break;
            }
        }
        if (needChangeOppo) {
            this.oppoIndex--;
        }
        this.oppoIndex = this.oppoIndex % this.opponents.length;
    }

    getOppo() {
        console.log(this.index, " vs ", this.opponents[this.oppoIndex]);
        return this.opponents[this.oppoIndex];
    }

    turnOnce() {
        this.oppoIndex++;
        this.oppoIndex = this.oppoIndex % this.opponents.length;
    }
}
export class MatchMaker2 {
    players: Player[];
    roundCount: number;
    init(num: number) {
        this.players = [];
        for (let index = 0, len = num; index < len; index++) {
            let player = new Player(index + 1);
            player.setOpponents(num);
            this.players.push(player);
        }

        this.roundCount = 0;
        console.log(" init finished -- ");
    }

    removePlayer(playerIndex: number) {
        for (let index = 0, len = this.players.length; index < len; index++) {
            let player = this.players[index];
            if (player.index === playerIndex) {
                this.players.splice(index, 1);
                break;
            }
        }
        for (let index = 0, len = this.players.length; index < len; index++) {
            let player = this.players[index];
            player.onRemovePlayer(playerIndex);
        }
        console.log("removePlayer: ", this.players);
    }

    turnOnce() {
        console.log("turnOnce : ", this.roundCount);
        for (let index = 0, len = this.players.length; index < len; index++) {
            let player = this.players[index];
            player.getOppo();
            player.turnOnce();
        }

        this.roundCount++;
    }

    // 这个是测试函数
    start() {
        this.init(8);
        this.turnOnce();
        this.turnOnce();
        this.removePlayer(5);
        this.turnOnce();
        this.turnOnce();
        this.turnOnce();
    }
}